package com.cloudinnov.websocket;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cloudinnov.utils.CommonUtils;
import com.fasterxml.jackson.core.JsonProcessingException;

/**
 * 电力监控告警推送
 * @ClassName: AlarmDialogueWebsocket
 * @Description: TODO
 * @author: icezhang
 * @date: 2016年10月17日 下午3:18:31
 */
@ServerEndpoint("/electricAlarm")
public class ElectricMonitorWebsocket {
	private static Logger logger = LoggerFactory.getLogger(ElectricMonitorWebsocket.class);
	private String random;
	// 静态变量，用来记录当前在线连接数。
	private static int onlineCount = 0;
	// 用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话，可以使用Map来存放，其中Key可以为用户标识
	public static ConcurrentMap<String, ElectricMonitorWebsocket> webSocketMap = new ConcurrentHashMap<String, ElectricMonitorWebsocket>();// 用来发送数据
	private Session session;
	
	/**
	 * 打开连接时触发
	 * @param relationId
	 * @param userCode
	 * @param session
	 * @throws IOException
	 * @throws JsonProcessingException
	 */
	@OnOpen
	public void onOpen(Session session) throws JsonProcessingException, IOException {
		this.session = session;
		this.random = CommonUtils.getUUID();
		webSocketMap.put(random, this);
		// 连接人数加1
		addOnlineCount();
		logger.debug("电力监控对话推送开始连接:" + random);
	}
	/**
	 * 收到客户端消息时触发 onMessage
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param @param select
	 * @param @param token
	 * @param @param message 参数
	 * @return void 返回类型
	 */
	@OnMessage
	public void onMessage(String message) {
		
	}
	/**
	 * 异常时触发
	 * @param relationId
	 * @param userCode
	 * @param session
	 */
	@OnError
	public void onError(Throwable throwable, Session session) {
		logger.error("电力监控对话推送异常:" + random);
		logger.error(throwable.getMessage(), throwable);
	}
	/**
	 * 关闭连接时触发
	 * @param relationId
	 * @param userCode
	 * @param session
	 */
	@OnClose
	public void onClose(Session session) {
		webSocketMap.remove(random);
		subOnlineCount(); // 在线数减1
		logger.debug("电力监控对话推送连接关闭:" + random);
	}
	/**
	 * 推送工单消息
	 * @param message
	 * @throws IOException
	 */
	public synchronized void sendMessage(String message) throws IOException {
		this.session.getBasicRemote().sendText(message);
	}
	public static synchronized int getOnlineCount() {
		return onlineCount;
	}
	public static synchronized void addOnlineCount() {
		ElectricMonitorWebsocket.onlineCount++;
	}
	public static synchronized void subOnlineCount() {
		ElectricMonitorWebsocket.onlineCount--;
	}
	
	
}
